//
//  FXCStatusCacheTool.m
//  XinLangFeiBo
//
//  Created by dllo on 16/3/2.
//  Copyright © 2016年 dllo. All rights reserved.
//

#import "FXCStatusCacheTool.h"
#import "FXCStatus.h"
#import <FMDatabase.h>
#import <MJExtension.h>
#import "FXCAccount.h"
#import "FXCStatus.h"
static FMDatabase *_db;

@implementation FXCStatusCacheTool

+ (void)initialize{
//    创建FMDatabase

    _db = [FMDatabase databaseWithPath:FXCStatusFile];
    
    
//    打开数据库
    if ([_db open]) {
//        创建表
        BOOL success = [_db executeUpdate:@"create table if not exists t_status (id integer primary key autoincrement,idstr text not null,dict blob not null,access_token text not null);"];
        if (success) {
            NSLog(@"创建成功");
        } else {
            NSLog(@"创建失败");
        }
    } else {
        NSLog(@"打开失败");
    }
    
}

+ (void)saveWithStatus:(NSArray *)dictArr{
    FXCAccount *account = [NSKeyedUnarchiver unarchiveObjectWithFile:FXCAccountFile];
    for (NSDictionary *dict in dictArr) {
        
        NSData *data = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:nil];
        BOOL success =[_db executeUpdate:@"insert into t_status (idstr,access_token,dict) values(?,?,?)",dict[@"idstr"],account.access_token,data];
        if (success) {
//            NSLog(@"插入成功");
            
        } else {
            NSLog(@"插入失败");
        }
    }
}

+ (NSArray *)statusesWithParam:(NSDictionary *)param
{
    FXCAccount *account = [NSKeyedUnarchiver unarchiveObjectWithFile:FXCAccountFile];
    FMResultSet *set;
    if (param[@"max_id"]) {
        set = [_db executeQuery:@"select * from t_status where access_token = ? and idstr <= ? order by idstr desc limit 20",account.access_token,param[@"max_id"]];
    }else if (param[@"since_id"] && !param[@"since_id"] == 0){
        set = [_db executeQuery:@"select * from t_status where access_token = ? and idstr > ? order by idstr desc limit 20",account.access_token,param[@"since_id"]];
    }else{
        
        set = [_db executeQuery:@"select * from t_status where access_token = ? order by idstr desc limit 20",account.access_token];
    }
    
    NSMutableArray *arrM = [NSMutableArray array];
    while ([set next]) {
        NSData *data = [set dataForColumn:@"dict"];
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        FXCStatus *s = [FXCStatus mj_objectWithKeyValues:dict];
        [arrM addObject:s];
    }
    
    return arrM;
}

@end
